/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-09-29 11:59:37
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-10-15 17:02:50
 * @FilePath: /react18-vite-admin/src/service/user/useUserDetail.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { useState } from 'react';

import { readUserDetail, UserParam, createOrUpdateUser } from '@/api/user';
import type { UserDetail } from '@/typings/api/user';

import { useStateRef } from '../../useStateRef';

export const useUserDetail = () => {
    const [detail, setDetail] = useState<UserDetail>();
    const [loading, loadingRef, setLoading] = useStateRef(false);

    const getDetail = (id: number) => {
        if (loadingRef.current) return;
        setLoading(true);
        return readUserDetail(id)
            .then((res) => {
                setDetail(res.data);
                return res;
            })
            .finally(() => {
                setLoading(false);
            });
    };

    const [saveLoading, saveLoadingRef, setSaveLoading] = useStateRef(false); 
    const saveUser = (param: UserParam) => {
        console.log(param);
        if (saveLoadingRef.current) return Promise.reject();
        setSaveLoading(true);
        return createOrUpdateUser(param).finally(() => {
            setSaveLoading(false);
        });
    };

    return {
        detail,
        loading,
        getDetail,
        saveLoading,
        setSaveLoading,
        saveUser
    };
};
